package com.tsing.cedap.rest.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.tsing.cedap.common.config.RedisManager;
import com.tsing.cedap.common.constants.AuthConstant;
import com.tsing.cedap.common.exceptions.BusinessException;
import com.tsing.cedap.common.exceptions.CommonException;
import com.tsing.cedap.common.utils.GetLoginUserUtil;
import com.tsing.cedap.common.vo.UserVo;
import com.tsing.cedap.rest.entity.UserEntity;
import com.tsing.cedap.rest.mapper.UserMapper;
import com.tsing.cedap.rest.service.IMiniCommonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * @author TheTsing
 * @create 2022-02-25 9:43
 */
@Service
public class MiniCommonServiceImpl implements IMiniCommonService {

    @Autowired
    private RedisManager redisManager;

    @Resource
    private UserMapper userMapper;

    @Override
    public void becomeRider(HttpServletRequest request) {
        String token = request.getHeader(AuthConstant.AUTHENTICATION_HEAD);
        UserVo userVo = GetLoginUserUtil.getLoginUserInfo(token, redisManager);
        if (ObjectUtil.isNull(new LambdaQueryChainWrapper<>(userMapper)
                .select(UserEntity::getId)
                .eq(UserEntity::getId, userVo.getId())
                .eq(UserEntity::getIsRider, 0)
                .last("LIMIT 1")
                .one())) {
            throw new BusinessException(CommonException.Proxy.USER_IS_NOT_ALLOW_CHANGE);
        }
        new LambdaUpdateChainWrapper<>(userMapper)
                .set(UserEntity::getIsRider, 1)
                .eq(UserEntity::getId, userVo.getId())
                .update();

    }
}
